package com.liuc.practice.server.pojo;

import com.liuc.practice.server.util.HttpProtocolResponseUtil;
import com.liuc.practice.server.util.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author Liu Chang
 * @Date 2021/7/22 1:40 下午
 */
public class Response {

    private OutputStream outputStream;

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public Response() {

    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void outputHtml(String resourcesName) throws IOException {
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(resourcesName);

        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()) {
            // 输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 404
            output(HttpProtocolResponseUtil.notFound());
        }
    }

    public void output(String str) throws IOException {
        outputStream.write(str.getBytes());
    }
}
